// 加密解密封装
import CryptoJS from 'crypto-js';

// 十六位十六进制数作为密钥
const SECRET_KEY = CryptoJS.enc.Utf8.parse('3333e6e143439161');
// 十六位十六进制数作为密钥偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse('e3bbe7e3ba84431a');
// crypto加密
export const crypto = {

    /**
     * 加密方法
     * @param strVal
     * @returns {string}
     */
    encrypt: function(strVal) {
        const dataHex = CryptoJS.enc.Utf8.parse(strVal);
        const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
            iv: SECRET_IV,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
        });
        return encrypted.ciphertext.toString();
    },

    /**
     * 解密方法
     * @param data
     * @returns {string}
     */
    decrypt: function(strVal) {
        const encryptedHexStr = CryptoJS.enc.Hex.parse(strVal);
        const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
            iv: SECRET_IV,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
        });
        const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    },
};
// Base64 加密
export const base64 = {
    // 加密
    encode(str) {
        return btoa(
            encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {
                return String.fromCharCode(Number(`0x${p1}`));
            }),
        );
    },
    // 解密
    decode(str) {
        // Going backwards: from bytestream, to percent-encoding, to original string.
        return decodeURIComponent(
            atob(str)
                .split('')
                .map(function(c) {
                    return `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`;
                })
                .join(''),
        );
    },
};
